package com.wisewin.pose.util.wechatOffice;

import com.wisewin.pose.util.JedisUtil;
import com.wisewin.pose.util.wechatOffice.config.RedisProperties;
import com.wisewin.pose.util.wechatOffice.exception.ExpiredQrCodeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class WechatRedisUtils {
    @Autowired
    RedisProperties redisProperties;

    /**
     * 生成二维码时调用，把二维码的标识存入redis，标记为wait等待扫描
     * @param qrId
     */
    public void saveQrId(String qrId){
        JedisUtil.setEx(redisProperties.getPrefix()+":"+qrId, "wait", redisProperties.getQrExpiredMinute() * 60 * 1L);
    }

    /**
     * 扫描二维码后调用，将redis里的wait标记替换为用openid
     * @param qrId
     * @param openid
     */
    public void scanQr(String qrId,String openid){
        JedisUtil.setEx(redisProperties.getPrefix()+":"+qrId, openid, 1 * 60 * 1L);
    }

    /**
     * 页面轮询的时候调用，根据二维码标识获取里面存的openid，如果里面还是wait，则返回null
     * @param qrId 二维码标识
     * @return
     */
    public String getOpenid(String qrId) throws ExpiredQrCodeException {
        String s = JedisUtil.get(redisProperties.getPrefix() + ":" + qrId);
        if(s==null){
            throw new ExpiredQrCodeException("二维码已过期");
        }
        if(s.equals("wait")){
            return null;
        }
        return s;
    }
}
